<?php
class SitemapController 
	extends Zend_Controller_Action 
{
	
	public function indexAction()
	{
		$siteMap = new My_SiteMap();
		$config = Zend_Registry::get('configuration');
		
		
		$mapper1 = Delivery_Model_Factory::mapper( 'Negocios' );
		$mapper2 = Delivery_Model_Factory::mapper( 'Direcciones' );
		$mapper3 = Delivery_Model_Factory::mapper( 'Tags' );
		$mapper4 = Delivery_Model_Factory::mapper( 'Ciudades' );
		
		$negocios    = $mapper1->all();
		$ciudades    = $mapper4->getByIds($mapper2->ciudades());
        $tags        = $mapper3->getLinked();
		
        $date = Zend_Date::now();
		$lastmod = $date->toString(Zend_Date::ISO_8601);
		
		$serverUrl = str_replace("cron.", null, $this->view->serverUrl());
		
		// Static
		$dom = new DOMDocument('1.0', 'UTF-8');
		$dom->load( $config->routesFile );
		$xp = new DOMXpath($dom);		
				
		$results = $xp->query('//*[@sitemap="true"]');
									
		foreach ($results as $result){
		
			$siteMap->addItem(
                $serverUrl . $this->getHelper('Url')->url(array(), $result->nodeName),
		        $lastmod,
		        My_SiteMap::FREQUENCY_WEEKLY,
		        0.5
		    );
			
		}	
		
		// Negocios
		foreach ($negocios as $negocio){
		
		    $siteMap->addItem(
                $serverUrl . $this->getHelper('Url')->url(array('negocioUrl' => $this->view->varUrl($negocio->url)), 'negocio'),
		        $lastmod,
		        My_SiteMap::FREQUENCY_WEEKLY,
		        0.5
		    );
		}
		
//		// Negocios
//		foreach ($negocios as $negocio){
//		
//		    $siteMap->addItem(
//                $serverUrl . $this->getHelper('Url')->url(array('negocioUrl' => $this->view->varUrl($negocio->url)), 'negocio'),
//		        $lastmod,
//		        My_SiteMap::FREQUENCY_WEEKLY,
//		        0.5
//		    );
//		}
		
	    // Ciudades
		foreach ($ciudades as $ciudad){
		
		    $siteMap->addItem(
                $serverUrl . $this->getHelper('Url')->url(array('ciudad' => $this->view->varUrl($ciudad->nombre), 'provincia' => $this->view->varUrl($ciudad->provincia)), 'ciudad'),
		        $lastmod,
		        My_SiteMap::FREQUENCY_WEEKLY,
		        0.5
		    );
		}
		
	    // Tags
        foreach ($tags as $tipo=>$data){
		
            if($tipo == 'barrio'){
                continue;
            }
            
    		foreach ($data as $dat){
    			
    			$tag = $dat['tag'];
    			
    			$siteMap->addItem(
                    $serverUrl . $this->getHelper('Url')->url(array('tagName' => $this->view->varUrl($tag->nombre)), $tipo),
    		        $lastmod,
    		        My_SiteMap::FREQUENCY_WEEKLY,
    		        0.5
    		    );
    		}
	    }	
		
		
	    
//		if( file_exists( $config->sitemapFile )){
//			unlink( $config->sitemapFile );
//		}
		
		$siteMap->save( $config->sitemapFile );
		
		
		
		echo $siteMap->saveXML();
	}
	
	
}